public class Test17 {
    public static String compress(String str) {
        if (str == null || str.isEmpty()) {
            return str;
        }
        StringBuilder compressed = new StringBuilder();
        int count = 1;
        char current = str.charAt(0);

        for (int i = 1; i < str.length(); i++) {
            if (str.charAt(i) == current) {
                count++;
            } else {
                compressed.append(current).append(count);
                current = str.charAt(i);
                count = 1;
            }
        }
        // 添加最后一个字符及其计数
        compressed.append(current).append(count);

        // 只有当压缩后的字符串比原字符串短时才返回
        return compressed.length() < str.length() ? compressed.toString() : str;
    }

    public static void main(String[] args) {
        String input = "aaabbbcc";
        String compressed = compress(input);
        System.out.println("原始字符串: " + input);
        System.out.println("压缩结果: " + compressed);
    }
}